package com.otaku.admin.handle;

import com.alibaba.fastjson.JSONObject;
import com.otaku.admin.exception.CheckParamsException;
import com.otaku.admin.util.ResultEnum;
import com.otaku.admin.util.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 该异常拦截类 不要全局拦截 Exception 会将登陆校验 权限拦截等的异常处理拦截
 * 如需全局拦截，需将所有可预见的登陆及权限及其他指定类型的异常先拦截，最后拦截 Exception
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * CheckParamsException 异常拦截
     *
     */
    @ExceptionHandler(value = CheckParamsException.class)
    public String allExceptionHandler(HttpServletRequest request, Exception exception) {
        String exNm = exception.getClass().getName();
        logger.error("{}请求出现异常:{}", request.getRequestURI(), exNm, exception);
        return JSONObject.toJSONString(ResultVO.result(ResultEnum.CHECK_PARAMS, false));
    }
}

